package com.cheng.chengrobot.handler.messageForwardHandler;

import com.cheng.chengrobot.domain.MessageForward;
import com.cheng.chengrobot.service.MessageForwardService;
import com.cheng.chengrobot.service.RobotService;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.PlainText;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class GroupMessageForwarder
        extends SimpleListenerHost
{

    @Autowired
    MessageForwardService messageForwardService;

    @Autowired
    RobotService robotService;

    @EventHandler
    public void forwardGroupMessage(@NotNull GroupMessageEvent event) throws Exception { // 可以抛出任何异常, 将在 handleException 处理
        //获取收信机器人qq号，群号以及发送者QQ号
        Long robotQq = event.getBot().getId();
        Long GroupQq = event.getGroup().getId();
        Long senderQq = event.getSender().getId();

        //判断机器人的消息转发是否开启
        if (!robotService.isForwardTurnedOn(robotQq))
        {
            return;
        }

        //获取消息转发列表
        List<MessageForward> messageForwardList = messageForwardService.getMessageForward(robotQq, null, GroupQq,
                                                                                          senderQq);
        //给列表里所有的接收者转发
        for (MessageForward messageForward : messageForwardList)
        {
            //必须要那个机器人的消息转发功能开启且这条消息转发处于激活状态才能转发
            if (messageForward.getActive() && robotService.isForwardTurnedOn(messageForward.getToRobotQq()))
            {

                Bot toRobot = Bot.getInstance(messageForward.getToRobotQq());
                //如果设置了转发到群就转发到那个群，设置了转发到好友就转发到好友
                if (messageForward.getToGroup() != null)
                {
                    //在消息链前面添加fix
                    MessageChain chain = event.getMessage();
                    toRobot.getGroup(messageForward.getToGroup()).sendMessage(
                            new PlainText(messageForward.getFix()).plus(chain));
                }

                if (messageForward.getToQq() != null)
                {
                    //在消息链前面添加fix
                    MessageChain chain = event.getMessage();
                    toRobot.getFriend(messageForward.getToQq()).sendMessage(
                            new PlainText(messageForward.getFix()).plus(chain));
                }
            }
        }
    }
}
